﻿using System;
using System.Configuration;
using System.IO;
using System.Text;
using HJT212_Protocol_DAL.DAO;
using SailHero.Soft.ESB.Communication.ClientAndServer.Communication.Messages;
using SailHero.Soft.ESB.Communication.ClientAndServer.Communication.Protocols.BinarySerialization;

namespace HJ212_Protocol
{
    /// <summary>
    /// This class is a sample custom wire protocol to use as wire protocol in SailHero.Soft.ESB framework.
    /// It extends BinarySerializationProtocol.
    /// It is used just to send/receive TextMessage messages.
    /// 
    /// Since BinarySerializationProtocol automatically writes message length to the beggining
    /// of the message, a message format of this class is:
    /// 
    /// [Message length (4 bytes)][UTF-8 encoded text (N bytes)]
    /// 
    /// So, total length of the message = (N + 4) bytes;
    /// </summary>
    public class MyWireProtocol : BinarySerializationProtocol
    {

        protected override byte[] SerializeMessage(IMessage message)
        {

            Message msg = new Message();
            msg.From = message.FromMN;
            msg.To = message.To;

            message.To =
                message.FromMN = string.Empty;

            msg.Head = "##";

            if (message is TextMessage)
            {
                msg.Content = Encoding.ASCII.GetBytes(((TextMessage)message).Text);
            }
            msg.Size = ((TextMessage)message).Text.Length;//当需要分包处理时再行考虑，此时只是一个单一的数据包

            //msg.CRC = 0xffff;
            if (string.IsNullOrEmpty(msg.From))
            {
                string IDCode = ConfigurationManager.AppSettings["MN"];
                msg.From = string.Format("{0}{1}", IDCode, "");
            }
            if (string.IsNullOrEmpty(msg.To))
            {
                msg.To = "不知道哪";
            }
            byte[] _byte = msg.ToBytes();
            return _byte;
        }

        protected override IMessage DeserializeMessage(byte[] bytes)
        {
            //Decode UTF8 encoded text and create a TextMessage object
            Message msg = Message.FromBytes(bytes);
            if (msg.Head == "##")
            {
                TextMessage Tmsg = new TextMessage(Encoding.ASCII.GetString(msg.Content));
                //Tmsg.FromMN = msg.MN;
                Tmsg.To = msg.To;
                Tmsg.MsgType = msg.MsgType;
                Tmsg.MN = msg.MN;
                Tmsg.PW = msg.PW;
                Tmsg.QN = msg.QN;
                Tmsg.CN = msg.CN;
                Tmsg.CP = msg.CP;
                Tmsg.Flag = msg.Flag;
                Tmsg.ST = msg.ST;
                return Tmsg;
            }
            return null;

        }

    }
}
